import { createSSRApp } from "vue";
import App from "./App.vue";
import { Env } from '@/easy-uni3/env'
import { errorHandler, warnHandler } from '@/easy-uni3/global/exception'
// import { placeholder, yangMoney, fnumber, formatDate, enums } from '@/easy-util-ts/format';
import { placeholder, yangMoney, fnumber, formatDate, enums } from '@easyproduce/easy-util-ts/format';
import { createPinia } from 'pinia'
import piniaPersist from 'pinia-plugin-persist-uni'
import SnowflakeId from "snowflake-id";
import uvUi from '@climblee/uv-ui'
import { initRequest } from '@/easy-uni3/request';
import '@/lib/event'
import {
	fetchUserinfo,
	getEmplyeePersonInfoOld,
} from "@/model";
export function createApp() {

	// 创建app
	const app = createSSRApp(App);

	// 环境变量
	const env = new Env();
	// 当前客户端
	const uniqueId = (new SnowflakeId()).generate();

	// 全局格式化函数
	app.config.globalProperties.$ftext = placeholder;
	app.config.globalProperties.$fdate = formatDate;
	app.config.globalProperties.$fmoney = yangMoney;
	app.config.globalProperties.$fnumber = fnumber;
	app.config.globalProperties.$fenum = enums;

	app.config.globalProperties.$pUrl = (form:any, keys:any) => {
		if (!form) return {};
		if (!keys) return form;
		keys.forEach((key:any) => {
			if (form[key] && form[key].type) {
				form[key] = form[key].url;
			}
		})
		return form;
	}
	
	app.config.globalProperties.$home = () => {
		uni.redirectTo({
			url: '/page/home/index',
		})
	}
	function dynamicEmpty(fields: any[]) {
		if (!fields) return true;
		let showArchives = uni.getStorageSync('positionShowArchives') || [];
		let map = showArchives.reduce((r: any, i: any) => (r[i] = true, r), {});
		let result = fields.some(i => map[i]);
		return !result;
	}

	app.config.globalProperties.$dynamicEmpty =dynamicEmpty

	app.config.globalProperties.$fetchInfo = async () => {
		let userId = uni.getStorageSync('userId');
		if (!userId) {
			uni.redirectTo({
				url: 'SwitchLogin'
			})
			return;
		}
		uni.showLoading()
		try{
			let isOld = uni.getStorageSync('archives_status') === 2;
			if (!isOld) {
				let {data} = await fetchUserinfo({id: userId});
				let objKeys = Object.keys(data);
				objKeys.map(keyItem => {
					if (data[keyItem] === '0000-00-00') {
						data[keyItem] = ''
					}
					return keyItem
				})
				uni.setStorageSync('userStatus', data.status);
				uni.setStorageSync('archives_status', data.archives_status)
				return data;
			} else {
				let {data} = await getEmplyeePersonInfoOld({id: userId});
				let objKeys = Object.keys(data);
				objKeys.map(keyItem => {
					if (data[keyItem] === '0000-00-00') {
						data[keyItem] = ''
					}
					return keyItem
				})
				uni.setStorageSync('userStatus', data.status);
				uni.setStorageSync('archives_status', data.archives_status)
				return data;
			}
		}catch(e){
			//TODO handle the exception
		} finally {
			uni.hideLoading()
		}
		
	}
	


	const envjudge = function() {
    var isMobile = window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i); // 是否手机端
    var isWx = /micromessenger/i.test(navigator.userAgent); // 是否微信
    var isComWx = /wxwork/i.test(navigator.userAgent); // 是否企业微信
            
    if (isComWx && isMobile) { //手机端企业微信
        return 'com-wx-mobile'
    }
    else if (isComWx && !isMobile) { //PC端企业微信
        return 'com-wx-pc'
    }
    else if (isWx && isMobile) { // 手机端微信
        return 'wx-mobile';
    }
    else if (isWx && !isMobile) { // PC端微信
        return 'wx-pc';
    }
    else {
        return 'other';
    }
	}
	app.config.globalProperties.$envjudge = envjudge;
	// 全局注入
	app.provide('global', { env, uniqueId })

	// 回调处理
	setTimeout(() => {
		app.config.errorHandler = errorHandler;
		app.config.warnHandler = warnHandler;
	})

	// 实例化 pinia
	const pinia = createPinia()
	pinia.use(piniaPersist)  // 持久化

	app.use(pinia)

	// 导入uView
	app.use(uvUi)

	// 对request注入配置
	initRequest(app);

	return { app };
}